import type {
  ReactNode,
  Ref,
} from 'react'
import {
  createContext,
  useContext,
  useRef,
} from 'react'

const SandboxEleContext = createContext<
  [
    Ref<HTMLIFrameElement | null>,
    (sandboxEle: HTMLIFrameElement | null) => void,
  ] | null
      >(null)
function SandboxEleProvider({ children }: { children: ReactNode }) {
  const sandboxEleRef = useRef<HTMLIFrameElement | null>(null)
  const updateSandboxEle = (sandboxEle: HTMLIFrameElement | null) => {
    sandboxEleRef.current = sandboxEle
  }
  return (
    <SandboxEleContext.Provider value={[sandboxEleRef, updateSandboxEle]}>
      {children}
    </SandboxEleContext.Provider>
  )
}

function useSandboxEle() {
  const context = useContext(SandboxEleContext)
  if (!context)
    throw new Error('useSandboxEle must be used within a SandboxEleProvider')

  return context
}
export { SandboxEleProvider, useSandboxEle }
